import { useState, useEffect, useRef } from 'react';

export function useTimer() {
    const [time, setTime] = useState(0); // 计时的秒数
    const [isRunning, setIsRunning] = useState(false); // 是否正在计时
    const intervalRef: any = useRef(null); // 保存interval id，方便清除

    // 开始计时
    const startRunTimer = () => {
        setIsRunning(true);
    };

    // 停止计时
    const stopRunTimer = () => {
        setIsRunning(false);
    };

    // 重置计时
    const resetRunTimer = () => {
        setIsRunning(false);
        setTime(0);
    };

    useEffect(() => {
        if (isRunning) {
            intervalRef.current = setInterval(() => {
                setTime(prevTime => prevTime + 1); // 每秒增加1秒
            }, 1000);
        } else if (intervalRef.current) {
            clearInterval(intervalRef.current);
            intervalRef.current = null;
        }

        // 清除interval
        return () => clearInterval(intervalRef.current);
    }, [isRunning]);

    // 格式化时间为 MM:SS
    const formattedTime = () => {
        const minutes = String(Math.floor(time / 60)).padStart(2, '0');
        const seconds = String(time % 60).padStart(2, '0');
        return `${minutes}:${seconds}`;
    };

    return { time: formattedTime(), startRunTimer, stopRunTimer, resetRunTimer };
}

